package com.glsc.ngateway.common.base.repo;

import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.Iterator;

public class BaseRepositoryImpl <T,ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseRepository<T, ID> {

	private static final int BATCH_SIZE = 500;
	 
    private EntityManager em;
 
    public BaseRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager em) {
        super(entityInformation, em);
        this.em = em;
 
    }
 
    public BaseRepositoryImpl(Class<T> domainClass, EntityManager em) {
        super(domainClass, em);
        this.em = em;
    }

    @Override
    @Transactional
    public <S extends T> Iterable<S> batchInsert(Iterable<S> var1) {
    	 Iterator<S> iterator = var1.iterator();
         int index = 0;
         while (iterator.hasNext()){
             em.persist(iterator.next());
             index++;
             if (index % BATCH_SIZE == 0){
                 em.flush();
                 em.clear();
             }
         }
         if (index % BATCH_SIZE != 0){
             em.flush();
             em.clear();
         }
         return var1;
    }

    @Override
    @Transactional
    public <S extends T> Iterable<S> batchUpdate(Iterable<S> var1) {
        Iterator<S> iterator = var1.iterator();
        int index = 0;
        while (iterator.hasNext()){
            em.merge(iterator.next());
            index++;
            if (index % BATCH_SIZE == 0){
                em.flush();
                em.clear();
            }
        }
        if (index % BATCH_SIZE != 0){
            em.flush();
            em.clear();
        }
        return var1;
    }
    
//    @Override
//    @Transactional
//    public List<Integer> batchExecNativeSql(List<String> sqls) {
//    
//    	
//    	em.setFlushMode(FlushModeType.AUTO);
//    	Query query = em.createQuery("update ExecResult set taskDefId=?1 where execId=?2");
//    	
//    	List<Integer> ret = new ArrayList<Integer>();
//    	for(int i=0;i<sqls.size();i++) {
//    		
//    		query.setParameter(1, "task");
//    		query.setParameter(2, "execid_"+(i+1));
//    		
////    		Query query = em.createNativeQuery(sqls.get(i));
////    		Query query = em.createQuery(sqls.get(i));
//    		query.setParameter(1, "task");
//    		query.setParameter(2, "execid_"+i);
//    		int r = query.executeUpdate();
//    		if (i % BATCH_SIZE == 0){
//                em.flush();
//                em.clear();
//            }
//    		ret.add(r);
//    	}
//    	em.flush();
//        em.clear();
//        
//        return ret;
//    	
//    }
}
